// 导入express框架
var express = require("express");
// 导入router后面导出
var router = express.Router();
//导入 moment
const moment = require("moment");

const userModel = require("../../models/UserModel");

router.post("/create", function (req, res, next) {
  // 校验 name 字段
  if (!req.body.name || req.body.name.length < 2 || req.body.name.length > 6) {
    res.json({
      code: "1001",
      msg: "name 字段必须为 2 到 6 个字符",
    });
    return;
  }
  const newData = { ...req.body, createTime: moment().format() };
  userModel.create(newData, (err, data) => {
    // console.log({...req.body});
    if (err) {
      res.json({
        code: "1002",
        msg: "创建失败~~",
        data: err,
      });
      return;
    }
    res.json({
      code: "0000",
      msg: "创建成功",
    });
  });
});

router.get("/userList", async (req, res) => {
  try {
    const page = req.query.page || 1;
    const pageSize = req.query.pageSize || 5;
    const name = req.query.name || "";

    const query = name ? { name: { $regex: name, $options: "i" } } : {};

    // const totalItems = await userModel.countDocuments(query);
    const totalItems = await userModel.countDocuments(query);

    let list = await userModel
      .find(query)
      .select("-__v")
      .limit(parseInt(pageSize))
      .skip((page - 1) * pageSize);
    list = list.map((item) => {
      const { _id, ...rest } = item.toObject();
      return {
        ...rest, // 将剩余的字段保留
        createTime: moment(item.createTime).format("YYYY/MM/DD HH:mm:ss"),
        id: _id, // 将 `_id` 值赋给 `id` 字段
      };
    });
    res.json({
      code: "0000",
      msg: "成功",
      data: {
        list,
        page,
        pageSize,
        totalItems, // 添加 totalItems 字段
        currentPage: parseInt(page),
      },
    });
  } catch (err) {
    res.json({
      code: "1002",
      msg: "查询失败",
      data: err,
    });
  }
});

router.post("/checkUser", async function (req, res) {
  try {
    const { id } = req.body;
    let data = await userModel.findOne({ _id: id }).select("-__v");
    const { _id, ...re } = data.toObject();
    const dataS = {...re,id:_id}
    res.json({
      code: "0000",
      msg: "成功",
      data: dataS,  // 将新的data对象作为响应的数据
    });
  } catch (err) {
    res.json({
      code: "1002",
      msg: "查询失败",
      data: err,
    });
  }
});

router.post("/delUser", (req, res) => {
  userModel.deleteOne({ _id: req.body.id }, (err, data) => {
    if (err) {
      res.json({
        code: "1002",
        msg: "删除失败",
      });
    }
    res.json({
      code: "0000",
      msg: "删除成功",
    });
  });
});

router.post("/editUser", (req, res) => {
  if (!req.body.name || req.body.name.length < 2 || req.body.name.length > 6) {
    res.json({
      code: "1001",
      msg: "name 字段必须为 2 到 6 个字符",
    });
    return;
  }
  const newData = { ...req.body };
  userModel.updateOne({ _id: req.body.id }, newData, (err, data) => {
    if (err) {
      res.json({
        code: "1002",
        msg: "编辑失败",
      });
    }
    res.json({
      code: "0000",
      msg: "编辑成功",
    });
  });
});
module.exports = router;
